//
//  smcJuhuverse.m
//  juhu
//
//  Created by Christian Martick on 06.04.08.
//  Copyright 2008 Christian Martick. All rights reserved.
//

#import "smcJuhuverse.h"
#import "smcAsyncConnection.h"
#import "NSDictionary+BSJSONAdditions.h"

@implementation smcJuhuverse

@dynamic center;

#pragma mark -
#pragma mark helper

- (void) _loadUserImageFrom: (NSURL *) url withNick: (NSString *) nick
{
	// kick off image download
	smcAsyncConnection *connection = [[[smcAsyncConnection alloc] init] autorelease];
	[connection setDelegate: self];
	//and go for it
	[connection beginDownloadFromURL: url 
		withTimout: 20 
		userAgent: JUHUCLIENT_VERSION
		andInfo: [NSDictionary dictionaryWithObjectsAndKeys: @"userImage", @"kind",
			nick, @"nick", NULL]];}

- (void) _loadUserInfoFor: (NSString *) nick
{
	// kick of json download (nick.jaiku.com/json)
	smcAsyncConnection *connection = [[[smcAsyncConnection alloc] init] autorelease];
	[connection setDelegate: self];
	//and go for it
	[connection beginDownloadFromURL: [NSURL URLWithString: [NSString stringWithFormat: @"http://%@.jaiku.com/json", nick]] 
		withTimout: 20 
		userAgent: JUHUCLIENT_VERSION
		andInfo: [NSDictionary dictionaryWithObjectsAndKeys: @"jsonUserInfo", @"kind",
			nick, @"nick", NULL]];
}

#pragma mark -
#pragma mark init/dealloc

- (id) initWithJaikuAPI: (smcJaikuAPI *) apiobj
{
	self = [super init];
	if (self)
	{
		allPeople = [[NSMutableDictionary dictionaryWithCapacity: 20] retain];
		api = [apiobj retain];
		self.center = [api username];
	}
	return self;
}
- (void) dealloc
{
	[api release];
	[allPeople release];
	[centerNick release];
	[super dealloc];
}

#pragma mark -
#pragma mark set/get

- (void) setCenter: (NSString*) nick
{
	// and set nick
	if (centerNick != nick)
	{
		[centerNick release];
		centerNick = [nick retain];
		
		// even if therer isn't an image yet: kvc
		[self willChangeValueForKey: @"userImage"];
		[self didChangeValueForKey: @"userImage"];
	}	
	
	// if nick is already in the allPeople Dict, use that, otherwise: initate download of info
	if ([allPeople objectForKey: nick] == nil)
		[self _loadUserInfoFor: nick];
	else
	{
		// kvc notify, for the download this happens in the download delegate
		[self willChangeValueForKey: @"friends"];
		[self didChangeValueForKey: @"friends"];
	}
}

- (NSString *) getCenter
{
	return centerNick;
}

- (NSArray *) friends
{
	return [[allPeople objectForKey: centerNick] objectForKey: @"contacts"];
}

- (NSImage *) userImage
{
	return [[allPeople objectForKey: centerNick] objectForKey: @"userImage"];
}

#pragma mark -
#pragma mark smc async connection delegates

- (void) downloadFromURL: (NSURL *) url didFinishWithData: (NSData *) data andInfo: (id) info
{
	if ([[info objectForKey: @"kind"] isEqualToString: @"jsonUserInfo"])
	{
		// put data into string (clean up using smcJaikuAPI -makeCleanUTF8MutableStringFromData method)
		NSString *tmp = [NSString stringWithString: [api makeCleanUTF8MutableStringFromData: data]];
		
		// ...parse into dict
		NSMutableDictionary *tmpDict = [NSMutableDictionary dictionaryWithDictionary: 
			[NSDictionary dictionaryWithJSONString: tmp]];
		
		// add to all persons and do kvc notify
		[self willChangeValueForKey: @"friends"];
		[allPeople setObject: tmpDict forKey: [tmpDict objectForKey: @"nick"]];
		[self didChangeValueForKey: @"friends"];

		// start image download
		// but before: post process url string - format issues...
		NSString *imageUrlString = [[tmpDict objectForKey: @"avatar"] stringByReplacingOccurrencesOfString: @"\\/"
		 withString: @"/"]; 

		[self _loadUserImageFrom: [NSURL URLWithString: imageUrlString] 
			withNick: [tmpDict objectForKey: @"nick"]];
		
		NSLog(@"info dload done for: %@", [tmpDict objectForKey: @"nick"]);
	} else if ([[info objectForKey: @"kind"] isEqualToString: @"userImage"])
	{
		// and there comes the image
		NSImage *img = [[[NSImage alloc] initWithData: data] autorelease];
		NSString *nick = [info objectForKey: @"nick"];

		// set (kvc)
		[self willChangeValueForKey: @"userImage"];
		[(NSMutableDictionary *)[allPeople objectForKey: nick] setObject: img forKey: @"userImage"];
		[self didChangeValueForKey: @"userImage"];
		
		NSLog(@"image d done :  %@", nick);
	}
}

- (void) downloadFromURL: (NSURL *) url didFailWithError: (NSError *) error andInfo: (id) info
{
	// for now: lets just ignore it...
}



@end
